package servlets;

import java.io.IOException;
import java.util.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Patient;
import model.PatientSearch;

/**
 * Servlet implementation class SearchServlet
 */
@WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchServlet() {
        super();
    }
    
    /**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
    	
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
			//request.getSession().invalidate(); // delete me!
			
			PatientSearch ps = new PatientSearch();
	
			HashMap<String, String> criteria = new HashMap<String, String>();
			List<String> allergies = new ArrayList<String>();
			List<String> medications = new ArrayList<String>();
			
			List<String> userEnteredCriteria = new ArrayList<String>();
			List<String> keys = new ArrayList<String>();
			
			HttpSession session = request.getSession();
			
			// get all criteria and put them into the hashmap
			if(!request.getParameter("firstName").equals(""))
				criteria.put("firstName", request.getParameter("firstName"));
			if(!request.getParameter("lastName").equals(""))
				criteria.put("lastName", request.getParameter("lastName"));
			if(!request.getParameter("race").equals("") && !request.getParameter("race").equals("--"))
				criteria.put("race", request.getParameter("race"));
			if(!request.getParameter("gender").equals("") && !request.getParameter("gender").equals("--"))
				criteria.put("gender", request.getParameter("gender"));
			if(!request.getParameter("insurance").equals(""))
				criteria.put("insurance", request.getParameter("insurance"));
			if(!request.getParameter("city").equals(""))
				criteria.put("city", request.getParameter("city"));
			if(!request.getParameter("state").equals(""))
				criteria.put("state", request.getParameter("state"));
			if(!request.getParameter("country").equals(""))
				criteria.put("country", request.getParameter("country"));
			if(!request.getParameter("bloodType").equals("") && !request.getParameter("bloodType").equals("--"))
				criteria.put("bloodType", request.getParameter("bloodType"));
			if(!request.getParameter("religion").equals(""))
				criteria.put("religion", request.getParameter("religion"));
			if(!request.getParameter("drLastName").equals(""))
				criteria.put("drLastName", request.getParameter("drLastName"));
			if(!request.getParameter("reason").equals(""))
				criteria.put("reason", request.getParameter("reason"));
			if(!request.getParameter("postalCode").equals(""))
				criteria.put("postalCode", request.getParameter("postalCode"));
				
			if(request.getParameterValues("allergies") != null)
			{
				allergies = Arrays.asList(request.getParameterValues("allergies"));
				if(!allergies.get(0).equals(""))
				{
					criteria.put("allergiesCombinationType", request.getParameter("allergiesCombinationType"));
				}
			}
			
			if(request.getParameterValues("medications") != null)
			{
				medications = Arrays.asList(request.getParameterValues("medications"));
				if(!medications.get(0).equals(""))
				{
					criteria.put("medicationsCombinationType", request.getParameter("medicationsCombinationType"));
				}
			}
			
			// If the DoB field is blank, use the range. 
			// If not, use the DoB for both min and max
			String DoBTemp = request.getParameter("DoB");
			String minAge = request.getParameter("minAge");
			String maxAge = request.getParameter("maxAge");
			
			if(DoBTemp.equals("") && !minAge.equals("") && !maxAge.equals(""))
			{
				// this converts the min age and max age to dates
				Calendar calMinAge = Calendar.getInstance();
				Calendar calMaxAge = Calendar.getInstance();
				int iMinAge = Integer.parseInt(request.getParameter("minAge"));
				int iMaxAge = Integer.parseInt(request.getParameter("maxAge"));
				
				calMinAge.set(calMinAge.get(Calendar.YEAR) - iMinAge, 
						calMinAge.get(Calendar.MONTH),
						calMinAge.get(Calendar.DATE));
	
				calMaxAge.set(calMaxAge.get(Calendar.YEAR) - iMaxAge, 
						calMaxAge.get(Calendar.MONTH),
						calMaxAge.get(Calendar.DATE));
				
				criteria.put("minAge", changeDateFormat((calMinAge.get(Calendar.MONTH) + 1)
										+ "/" + (calMinAge.get(Calendar.DATE))
										+ "/" + calMinAge.get(Calendar.YEAR)));
				criteria.put("maxAge", changeDateFormat((calMaxAge.get(Calendar.MONTH) + 1)
										+ "/" + (calMaxAge.get(Calendar.DATE))
										+ "/" + calMaxAge.get(Calendar.YEAR)));
			}
			else if(!DoBTemp.equals(""))
			{
				criteria.put("minAge", changeDateFormat(DoBTemp));
				criteria.put("maxAge", changeDateFormat(DoBTemp));
			}
			
			// If the Date of Visit field is blank, use the range. 
			// If not, use the Date of Visit for both min and max
			String dateOfVisit = request.getParameter("dateLastVisit");
			String minDateOfVisit = request.getParameter("dateLastVisitMin");
			String maxDateOfVisit = request.getParameter("dateLastVisitMax");
			if(dateOfVisit.equals("") && !minDateOfVisit.equals("") && !maxDateOfVisit.equals(""))
			{
				criteria.put("dateLastVisitMin", changeDateFormat(minDateOfVisit));
				criteria.put("dateLastVisitMax", changeDateFormat(maxDateOfVisit));
			}
			else if(!dateOfVisit.equals(""))
			{
				criteria.put("dateLastVisitMin", changeDateFormat(dateOfVisit));
				criteria.put("dateLastVisitMax", changeDateFormat(dateOfVisit));
			}
			
			Iterator<String> it = criteria.keySet().iterator();
			while(it.hasNext())
			{
				String temp = it.next();
				keys.add(temp);
				userEnteredCriteria.add(criteria.get(temp));
			}
			
			List<Patient> patientFiles = ps.search(criteria, allergies, medications);
			
			session.setAttribute("criteria", criteria);
			session.setAttribute("medications", medications);
			session.setAttribute("allergies", allergies);
			session.setAttribute("patientFiles", patientFiles);
			
			RequestDispatcher view = request.getRequestDispatcher("result.jsp");
			view.forward(request, response);
	
	}
	
	// takes in a string representing a date in the format of mm/dd/yyyy
	// and returns a string representing a date in the format of yyyy/mm/dd
	private String changeDateFormat(String date)
	{
		String result = null;
		String[] aDate;
		
		aDate = date.split("[/]");
		
		result = aDate[2] + "-" + aDate[0] + "-"  + aDate[1];
		
		return result;
	}
}
